<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>当当图书采集 for SHOPXO</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
</head>
<body class="index-search-index">
<div class="body-content-container">
    <div class="body-content-formal-container">
    <div class="nav-search white am-hide-sm-only">
        <div class="am-container">
            <div class="search-bar">
                <form action="admin_caiji.php?action=get" method="POST">
                    <div class="search-group am-radius am-nbfc">
                        <input id="bookisbn" name="bookisbn" type="text" placeholder="请输入书号" value="" autocomplete="off" />
                        <button type="submit" id="ai-topsearch" class="submit am-btn-primary">
                            <span>获取商品</span>
                        </button>
                    </div>
                </form>
             </div>
         </div>
    </div>
<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
if($_GET['action']=='get') {
	header("content-type:text/html;charset=utf-8");
	// 引入公共入口文件
	require __DIR__.'/core.php';
	// 加载基础文件
	require __DIR__ . '/../vendor/autoload.php';
	$header_search  = [
	    'Connection:keep-alive',
	    'Cookie:xxxxxxxxxxxx',
	    'Host:search.dangdang.com',
	    'Pragma:no-cache',
	    'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
	    'X-Requested-With:XMLHttpRequest',
	    'Upgrade-Insecure-Requests:1',
	];
	$header  = [
	    'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
	    'Accept-Encoding:gzip, deflate, br',
	    'Accept-Language:zh-CN,zh;q=0.9,en;q=0.8,ko;q=0.7',
	    'Connection:keep-alive',
	    'Cookie:yyyyyyyyyyyyyyy',
	    'Host:product.dangdang.com',
	    'Pragma:no-cache',
	    'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
	    'X-Requested-With:XMLHttpRequest',
	];
	$header_product  = [
	    'Content-Type:application/json;charset=utf-8',
	    'Connection:keep-alive',
	    'Cookie:zzzzzzzzzzzzzzz',
	    'Host:tooltt.com',
	    'Pragma:no-cache',
	    'Referer:https://tooltt.com/apitest/',
	    'Rhost:https://product.dangdang.com',
	    'X-Requested-With:XMLHttpRequest',
	    'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
	    ];
	$header_chinaz  = [
	    'Content-Type:application/x-www-form-urlencoded',
	    'Connection:keep-alive',
	    'Content-Length:369',
	    'Cookie:aaaaaaaaaaa',
	    'Origin:https://tool.chinaz.com',
	    'Pragma:no-cache',
	    'Referer:https://tool.chinaz.com/tools/httptest.aspx?utm_source=link.hacpai.com',
	    'X-Requested-With:XMLHttpRequest',
	    'Upgrade-Insecure-Requests:1',
	    'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
	    ];
	$header_xq = [
	    'Cache-Control:no-cache',
	    'Connection:keep-alive',
	    'Cookie:bbbbbbbbbbbb',
	    'Host:tooltt.com',
	    'Pragma:no-cache',
	    'Referer:https://tooltt.com/apitest/',
	    "Rhost:http://product.m.dangdang.com",
	    'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
	    'X-Requested-With:XMLHttpRequest',
	    'Upgrade-Insecure-Requests:1',
	    ];
	$headers = [];
	$bookisbn=$_POST['bookisbn'];
	$json = "";
	$isbn = $bookisbn;
	$url = "https://search.dangdang.com/?key=".$isbn."&act=input";
	$html=httpRequest($url,'GET',$json,$header_search);
	// 将网页内容转换为UTF-8编码
	$html = mb_convert_encoding($html, "UTF-8", "GBK");
	
	
	$str = 'no_result_tips';
	//检查是否无此书
	if (strpos($html, $str) !== false) {
		echo "\n=====================\n";
		echo "<span style='color:#f00;'><h1>当当网上查无此书！</h1></span>\n";
		echo "=====================\n";
		return;
	}
	
	//判断是否有电子书
	$start = '<div class="list_left" title="分类">分类</div>';
	$end   = 'style="display: none">更多</a>';
	$is_ebook_html = getStringBetween($html, $start, $end);
	$is_ebook = false;
	if (strpos($is_ebook_html, "电子书") !== false) {  
        $is_ebook = true;  
    }else{
        $is_ebook = false;
    }
    

	$start = '<div id="search_nature_rg" dd_name="普通商品区域">';
	$end = "</ul>";
	$html = getStringBetween($html, $start, $end);
	$html_search = $html;
	

	if($is_ebook){
	    $dom = new DOMDocument();  
        @$dom->loadHTML($html); // Suppress warnings  
        $liTags = $dom->getElementsByTagName('li');  
        if ($liTags->length > 1) {  
            $secondLi = $liTags->item(1); // Get the second li tag  
            $aTags = $secondLi->getElementsByTagName('a');  
            if ($aTags->length > 0) {  
                $caiji_url = $aTags->item(0)->getAttribute('href'); 
            }  
        } 
	}else{
	    $start_str = 'dd_name="单品图片" href="';
	    $end_str = '"';
	    $caiji_url = "https:".getStringBetween($html, $start_str, $end_str);
	}
	
	if($html=="") {
		$url = "https://search.dangdang.com/?key=".$isbn."&act=input";
		$html=httpRequest($url,'GET',$json,$header_search);
		// 将网页内容转换为UTF-8编码
		$html = mb_convert_encoding($html, "UTF-8", "GBK");
		$start = '<div id="search_nature_rg" dd_name="普通商品区域">';
		$end = "</ul>";
		$html = getStringBetween($html, $start, $end);
		if($is_ebook){
	        $dom = new DOMDocument();  
            @$dom->loadHTML($html); // Suppress warnings  
            $liTags = $dom->getElementsByTagName('li');  
            if ($liTags->length > 1) {  
                $secondLi = $liTags->item(1); // Get the second li tag  
                $aTags = $secondLi->getElementsByTagName('a');  
                if ($aTags->length > 0) {  
                    $caiji_url = $aTags->item(0)->getAttribute('href'); 
                }  
            } 
	    }else{
	        $start_str = 'dd_name="单品图片" href="';
		    $end_str = '"  target="_blank"';
	        $caiji_url = "https:".getStringBetween($html, $start_str, $end_str);
	    }
	}
	
	// 使用basename()函数获取文件名
	$filename = basename($caiji_url);
	// 去除文件名的扩展名
	$filenameWithoutExtension = pathinfo($filename, PATHINFO_FILENAME);
	$fn=$filenameWithoutExtension;

	// 商品地址
	//$url = 'https://product.dangdang.com/'.$fn.'.html';  // 替换为实际的商品地址
	// 商品地址
	//$url = 'https://tooltt.com/send/'.$fn.'.html';  // 替换为实际的商品地址
	$jsons = " ";
	$headers = [];
	// 通过商品地址获取页面内容
	//$html = httpRequest($url,'POST',$jsons,$header_product);
	// 将网页内容转换为UTF-8编码
	//$html = mb_convert_encoding($html, "UTF-8", "GBK");
	$url = 'https://tooltt.com/send/'.$fn.'.html';
	$html_tmp = httpRequest($url,'GET',$json,$header_xq);
	
	//$url = 'https://tooltt.com/send/29289621.html';
	//$html_tmp = httpRequest($url,'GET',$json,$header_xq);

	// 判断是否包含'<div class="nopage">'
    if (strpos($html_tmp, '<div class="nopage"') !== false) {
        $dom = new DOMDocument();  
        @$dom->loadHTML($html); // Suppress warnings  
        $liTags = $dom->getElementsByTagName('li');  
        if ($liTags->length > 1) {  
            $secondLi = $liTags->item(2); // Get the second li tag  
            $aTags = $secondLi->getElementsByTagName('a');  
            if ($aTags->length > 0) {  
                $caiji_url = $aTags->item(0)->getAttribute('href'); 
            }  
        } 
        // 使用basename()函数获取文件名
        $filename = basename($caiji_url);
        // 去除文件名的扩展名
        $filenameWithoutExtension = pathinfo($filename, PATHINFO_FILENAME);
        $fn=$filenameWithoutExtension;
        $url = 'https://tooltt.com/send/'.$fn.'.html';
	    $html = httpRequest($url,'GET',$json,$header_xq);
    }else{
        $html = $html_tmp;
    }
    

	$start= '<section class="turn">';
	$end ='<!-- 图文详情结束 -->';
	$result = getStringBetween($html, $start, $end);
	
	
	//判断是否能抓到分类
	$fenlei = preg_replace('/<[^>]+>/', '',getStringBetween($result,'<span class="linkto_value category_text">','</span>'));
	$elements = explode(">", $fenlei);
	if(isset($elements[0])) {
		$CategoryName = $elements[0];
	} else {
		$CategoryName = "";
	}
	if($CategoryName==''){
	    //echo '无法获取分类';
	    $dom = new DOMDocument();  
        @$dom->loadHTML($html_search); // Suppress warnings  
        $liTags = $dom->getElementsByTagName('li');  
        if ($liTags->length > 1) {  
            $secondLi = $liTags->item(1); // Get the second li tag  
            $aTags = $secondLi->getElementsByTagName('a');  
            if ($aTags->length > 0) {  
                $caiji_url = $aTags->item(0)->getAttribute('href'); 
            }  
        } 
        // 使用basename()函数获取文件名
        $filename = basename($caiji_url);
        // 去除文件名的扩展名
        $filenameWithoutExtension = pathinfo($filename, PATHINFO_FILENAME);
        $fn=$filenameWithoutExtension;
        $url = 'https://tooltt.com/send/'.$fn.'.html';
	    $html = httpRequest($url,'GET',$json,$header_xq);
	    
	    $start= '<section class="turn">';
	    $end ='<!-- 图文详情结束 -->';
	    $result = getStringBetween($html, $start, $end);
		
	}

	$new_price = getStringBetween($html,'"new_price":{"price_1":"','"');
	//echo $result;
	//exit;
	if($result=="") {
		echo "\n=====================\n\n";
		echo "<span style='color:#f00;'><h1>图书采集失败！\n\n当当采集Cookie失效，需要管理员重新初始化程序Cookie。</h1></span>\n\n";
		echo "=====================\n";
		return;
	}
	?>
	    <header class="am-topbar shop-navigation">
	        <div class="am-container">&nbsp;
	</div>
	    </header>
	    <div id="goods-category" class="am-container am-hide-sm-only am-hide-md-only" data-controller-name="search">
	       <div class="goods-category-s"><br><br><br>
	<?php
	$fenlei = preg_replace('/<[^>]+>/', '',getStringBetween($result,'<span class="linkto_value category_text">','</span>'));
	$elements = explode(">", $fenlei);
	if(isset($elements[0])) {
		$CategoryName = $elements[0];
	} else {
		$CategoryName = "";
	}
	if(isset($elements[1])) {
		$subCategoryName = $elements[1];
	} else {
		$subCategoryName = "";
	}
	if(isset($elements[2])) {
		$subSubCategoryName = $elements[2];
	} else {
		$subSubCategoryName ="";
	}
	echo "分类：";
	echo $CategoryName." | ".$subCategoryName." | ".$subSubCategoryName;
	echo "<br>";
	
	// 1、自动创建分类开始
	// 数据库连接配置
	$config = include('database.php');
	// 导入数据库连接配置
	try {
		// 连接数据库
		$dsn = $config['connections']['mysql']['type'] . ':host=' . $config['connections']['mysql']['hostname'] . ';dbname=' . $config['connections']['mysql']['database'] . ';port=' . $config['connections']['mysql']['hostport'];
		$username = $config['connections']['mysql']['username'];
		$password = $config['connections']['mysql']['password'];
		$options = $config['connections']['mysql']['params'];
		$pdo = new PDO($dsn, $username, $password, $options);
		// 检查一级分类是否存在
		//if($CategoryName=='图书'){$CategoryName='图书、童书';}
		$sql = "SELECT id FROM sxo_goods_category WHERE name = :name AND pid = 0";
		$stmt = $pdo->prepare($sql);
		$stmt->bindValue(':name', $CategoryName);
		$stmt->execute();
		$categoryId = $stmt->fetchColumn();
		if (!$categoryId) {
			// 创建一级分类
			$sql = "INSERT INTO sxo_goods_category (name, pid, add_time) VALUES (:name, 0, :add_time)";
			$stmt = $pdo->prepare($sql);
			$stmt->bindValue(':name', $categoryName);
			$stmt->bindValue(':add_time', time());
			$stmt->execute();
			$categoryId = $pdo->lastInsertId();
			echo "创建一级分类成功，分类ID为: " . $categoryId . "\n";
		} else {
			echo "一级分类已存在，分类ID为: " . $categoryId . "\n";
		}
		// 检查二级分类是否存在
		//$subCategoryName = '亲子/家教';
		$sql = "SELECT id FROM sxo_goods_category WHERE name = :name AND pid = :pid";
		$stmt = $pdo->prepare($sql);
		$stmt->bindValue(':name', $subCategoryName);
		$stmt->bindValue(':pid', $categoryId);
		$stmt->execute();
		$subCategoryId = $stmt->fetchColumn();
		if (!$subCategoryId) {
			// 创建二级分类
			$sql = "INSERT INTO sxo_goods_category (name, pid, add_time) VALUES (:name, :pid, :add_time)";
			$stmt = $pdo->prepare($sql);
			$stmt->bindValue(':name', $subCategoryName);
			$stmt->bindValue(':pid', $categoryId);
			$stmt->bindValue(':add_time', time());
			$stmt->execute();
			$subCategoryId = $pdo->lastInsertId();
			echo "创建二级分类成功，分类ID为: " . $subCategoryId . "\n";
		} else {
			echo "二级分类已存在，分类ID为: " . $subCategoryId . "\n";
		}
		// 检查三级分类是否存在
		//$subSubCategoryName = '亲子关系';
		$sql = "SELECT id FROM sxo_goods_category WHERE name = :name AND pid = :pid";
		$stmt = $pdo->prepare($sql);
		$stmt->bindValue(':name', $subSubCategoryName);
		$stmt->bindValue(':pid', $subCategoryId);
		$stmt->execute();
		$subSubCategoryId = $stmt->fetchColumn();
		if (!$subSubCategoryId) {
			// 创建三级分类
			$sql = "INSERT INTO sxo_goods_category (name, pid, add_time) VALUES (:name, :pid, :add_time)";
			$stmt = $pdo->prepare($sql);
			$stmt->bindValue(':name', $subSubCategoryName);
			$stmt->bindValue(':pid', $subCategoryId);
			$stmt->bindValue(':add_time', time());
			$stmt->execute();
			$subSubCategoryId = $pdo->lastInsertId();
			echo "创建三级分类成功，分类ID为: " . $subSubCategoryId . "\n";
		} else {
			echo "三级分类已存在，分类ID为: " . $subSubCategoryId . "\n";
		}
		//$pdo = null; // 关闭数据库连接
	}
	catch (PDOException $e) {
		echo "数据库操作失败: " . $e->getMessage();
	}

	// 1、自动创建分类结束
	$title = getStringBetween($result,'class="dangdang_icon">','</article>');
	if($title==""){
	    $title = '';
	    // 过滤HTML标签和空格
	    $title_tmp = getStringBetween($result,'<!-- 详情区域开始 -->','<div class="');
	    $filtered_string = strip_tags($title_tmp);
	    $filtered_string = trim($filtered_string);
	    $title = $filtered_string;
	}
	echo "<br>";
	echo "书名：";
	echo $title;
	echo "<br>";

	$title2 = trim(preg_replace('/<[^>]+>/', '',getStringBetween($result,'style="-webkit-line-clamp: 3;">','</div>')));
	echo "副标题：";
	echo $title2;
	echo "<br>";
	$shuhao = getStringBetween($result,'<li>国际标准书号','</li>');
	$shuhao = 'ISBN:'.$bookisbn;
	echo "书号：";
	echo $shuhao;
	echo "<br>";
	$shutu = getStringBetween($result,'<section id="slider">','<div class="dot">');
	// 创建一个新的DOMDocument对象
	$doc = new DOMDocument();
	// 通过加载HTML字符串来解析HTML
	$doc->loadHTML($shutu);
	// 使用DOMXPath来查询DOM文档
	$xpath = new DOMXPath($doc);
	// 查询所有img标签的src和imgsrc属性
	$images = $xpath->query("//img[@src or @imgsrc]");
	// 遍历查询结果并输出图片链接
	$count = 0;
	$imageUrl0 ="";
	$imageUrl_all = "";
	echo "书图：";
	foreach ($images as $image) {
		$src = $image->getAttribute('src');
		// 获取src属性的值
		$imgsrc = $image->getAttribute('imgsrc');
		// 获取imgsrc属性的值
		if (!empty($src)) {
			if($count==0) {
				$imageUrl0=$src;
			}
			$imageUrl = $src . "|";
			$imageUrl_all = $imageUrl_all.$imageUrl;
			$count++;
			echo '<img src="'.$src.'" style="width:100px;">';
		}
		if (!empty($imgsrc)) {
			if($count==0) {
				$imageUrl0=$imgsrc;
			}
			$imageUrl = $imgsrc . "|";
			$imageUrl_all = $imageUrl_all.$imageUrl;
			$count++;
			echo '<img src="'.$imgsrc.'" style="width:100px;">';
		}
	}
	echo "共找到{$count}张图片。";
	echo "<br>";
	if(substr($imageUrl_all, -1) === "|") {
		$imageUrl_all = substr($imageUrl_all, 0, strlen($imageUrl_all) - 1);
	}
	//echo $imageUrl_all;
	echo "<br>";
	echo "首图：";
	echo '<img src="'.$imageUrl0.'" style="width:100px;">';
	echo "<br>";
	$price =str_replace('&yen;','',preg_replace('/<[^>]+>/', '', trim(getStringBetween($result,'id="main_price">','</span>'))));
	if($price >$new_price) {
		$price=$new_price;
	}
	echo "售价：";
	echo $price;
	echo "<br>";
	$price_source =str_replace('&yen;','',preg_replace('/<[^>]+>/', '', trim(getStringBetween($result,'<div class="original_price">定价 <span class="line">&yen;','</span>'))));
	if($price_source=='') {
		$price_source = str_replace('&yen;','',preg_replace('/<[^>]+>/', '', trim(getStringBetween($result,"original-price&#39;>",'</div>'))));
	}
	echo "原价：";
	echo $price_source;
	echo "<br>";
	$discount = 0.3;
	// 三折折扣
	$price = floor($price_source * $discount * 10) / 10;
	//$url_yj = 'https://tooltt.com/send/index.php?r=callback%2Fproduct-info&productId='.$fn.'&isCatalog=0&shopId=0&productType=0';
	$url_yj = 'https://product.dangdang.com/index.php?r=callback%2Fproduct-info&productId='.$fn.'&isCatalog=0&shopId=0&productType=0';
	//$result_yj=httpRequest($url_yj,'GET',$json,$header);
	//$jsonObj_yj = json_decode($result_yj, true);
	//$price_yj = $jsonObj_yj['data']['spu']['price']['originalPrice'];
	//$salePrice = $jsonObj_yj['data']['spu']['price']['salePrice'];
	//echo "原价1：";
	//echo $price_yj;
	//echo "<br>";
	//echo "折扣价：";
	//echo $salePrice;
	//echo "<br>";
	if($salePrice!='') {
		if($salePrice<$price) {
			$price = $salePrice;
		}
	}
	$url = 'https://tooltt.com/send/'.$fn.'.html';
	$html = httpRequest($url,'GET',$json,$header_xq);
	//$start= '<li><a dd_name="顶部详情" href="';
	$start = '<a dd_name="顶部详情" href="';
	$end ='">';
	$url_xq = getStringBetween($html,$start,$end);
	
	
	//echo $url_xq;
	//http://product.m.dangdang.com/detail29480998-0-1.html?main_pid=&product_medium=0&category_id=51079&pod_pid=&category_path=01.07.21.03.00.00
	//exit;
	
	$url_xq = str_replace('http://product.m.dangdang.com','https://tooltt.com/send',$url_xq);
	$html_xq = httpRequest($url_xq,'GET',$json,$header_xq);
	
	//echo $html_xq;
	//exit;
	
	//$start= '产品特色】<br>';
	$start = '<!-- 九宫格图片 结束 -->';
	$end ='<!-- ##supplier_column_container## -->';
	$content_web = getStringBetween($html_xq,$start,$end);
	$content_web = str_replace("http://category.dangdang.com","#",$content_web);
	$content_web = str_replace("https://baike.baidu.com","#",$content_web);
	//echo $content_web;
	//$json = "";
	//$url_bookinfo = "https://wop.cc/get.php?fn=".$fn;
	//$content_web = httpRequest($url_bookinfo,'GET',$json,$header_product);
	//echo "图书说明：";
	//echo $content_web;
	//echo "<br>";
	//exit;
	try {
		// 2、新增商品
		// sxo_goods
		// 检查库中是否已有该书
		$sql = "SELECT id FROM sxo_goods WHERE title = :title";
		$stmt = $pdo->prepare($sql);
		$stmt->bindValue(':title', $title);
		$stmt->execute();
		$Boook_Id = $stmt->fetchColumn();
		if (!$Boook_Id) {
			$sql = "INSERT INTO sxo_goods (title, model, inventory_unit, images, original_price, min_original_price, max_original_price, price,min_price,max_price,content_web, photo_count,add_time, upd_time) VALUES ";
			$sql = $sql."(";
			$sql = $sql."'".$title."'".",";
			$sql = $sql."'".$shuhao."'".",";
			$sql = $sql."'本'".",";
			$sql = $sql."'".$imageUrl0."'".",";
			$sql = $sql.$price_source.",";
			$sql = $sql.$price_source.",";
			$sql = $sql.$price_source.",";
			$sql = $sql.$price.",";
			$sql = $sql.$price.",";
			$sql = $sql.$price.",";
			$sql = $sql.":content_web".",";
			$sql = $sql.$count.",";
			$sql = $sql.time().",";
			$sql = $sql.time();
			$sql = $sql.")";
			echo "\n2、新增商品：".$sql."\n";
			$stmt = $pdo->prepare($sql);
			$stmt->bindValue(':content_web', $content_web);
			$stmt->execute();
			// 获取插入的自增ID值
			$lastInsertId = $pdo->lastInsertId();
			// 3、新增商品所属分类，缺省加两条：
			// sxo_goods_category_join(goods_id,category_id,add_time)
			$sql = "INSERT INTO sxo_goods_category_join (goods_id,category_id,add_time) VALUES ";
			$sql = $sql."(";
			$sql = $sql.$lastInsertId.",";
			$sql = $sql.$subSubCategoryId.",";
			$sql = $sql.time();
			$sql = $sql.")";
			echo "\n3、新增商品所属分类：".$sql."\n";
			$stmt = $pdo->prepare($sql);
			$stmt->execute();
			// 4、新增商品加库存：
			// sxo_goods_spec_base (goods_id,price,original_price,inventory,add_time)
			$sql = "INSERT INTO sxo_goods_spec_base (goods_id,price,original_price,inventory,add_time) VALUES ";
			$sql = $sql."(";
			$sql = $sql.$lastInsertId.",";
			$sql = $sql.$price.",";
			$sql = $sql.$price_source.",";
			$kuchun = rand(1000, 10000);
			$sql = $sql.$kuchun.",";
			$sql = $sql.time();
			$sql = $sql.")";
			echo "\n4、新增商品加库存：".$sql."\n";
			$stmt = $pdo->prepare($sql);
			$stmt->execute();
			// 5、新增商品图，有几个图加几个图
			// sxo_goods_photo(goods_id,images,is_show,sort,add_time)
			// 创建一个新的DOMDocument对象
			$doc = new DOMDocument();
			// 通过加载HTML字符串来解析HTML
			$doc->loadHTML($shutu);
			// 使用DOMXPath来查询DOM文档
			$xpath = new DOMXPath($doc);
			// 查询所有img标签的src和imgsrc属性
			$images = $xpath->query("//img[@src or @imgsrc]");
			// 遍历查询结果并输出图片链接
			$sortcount = 0;
			foreach ($images as $image) {
			    $src = $image->getAttribute('src');
			    //获取src属性的值
			    $imgsrc = $image->getAttribute('imgsrc');
			    // 获取imgsrc属性的值
			    if (!empty($src)) {
			        $sql = "INSERT INTO sxo_goods_photo (goods_id,images,is_show,sort,add_time) VALUES ";
			        $sql = $sql."(";
			        $sql = $sql.$lastInsertId.",";
			        $sql = $sql."'".$src."'".",";
			        $sql = $sql."1".",";
			        $sql = $sql."'".$sortcount."'".",";
			        $sql = $sql.time();
			        $sql = $sql.")";
			        //echo "\n5、新增商品图：".$sql."\n";
			        $stmt = $pdo->prepare($sql);
			        $stmt->execute();
			        $sortcount++;
			    }
			    if (!empty($imgsrc)) {
			        $sql = "INSERT INTO sxo_goods_photo (goods_id,images,is_show,sort,add_time) VALUES ";
			        $sql = $sql."(";
			        $sql = $sql.$lastInsertId.",";
			        $sql = $sql."'".$imgsrc."'".",";
			        $sql = $sql."1".",";
			        $sql = $sql."'".$sortcount."'".",";
			        $sql = $sql.time();
			        $sql = $sql.")";
			        //echo "\n5、新增商品图：".$sql."\n";
			        $stmt = $pdo->prepare($sql);
			        $stmt->execute();
			        $sortcount++;
			    }
			}
			// 6、新增商品内容
			// sxo_goods_content_app(goods_id,images,content,add_time)
			$sql = "INSERT INTO sxo_goods_content_app(goods_id,images,content,add_time) VALUES ";
			$sql = $sql."(";
			$sql = $sql.$lastInsertId.",";
			$sql = $sql."'".$imageUrl0."'".",";
			$sql = $sql.":content_web".",";
			$sql = $sql.time();
			$sql = $sql.")";
			echo "\n6、新增商品内容：".$sql."\n";
			$stmt = $pdo->prepare($sql);
			$stmt->bindValue(':content_web', $content_web);
			$stmt->execute();
			// 7、库存处理
			// sxo_warehouse_goods(warehouse_id, goods_id,is_enable,inventory,add_time) 
			// sxo_warehouse_goods_spec(warehouse_goods_id, warehouse_id,goods_id,inventory,add_time) 
			$sql = "INSERT INTO sxo_warehouse_goods(warehouse_id, goods_id,is_enable,inventory,add_time) VALUES ";
			$sql = $sql."(";
			$sql = $sql."1,";
			$sql = $sql.$lastInsertId.",";
			$sql = $sql."1,";
			$sql = $sql.$kuchun.",";
			$sql = $sql.time();
			$sql = $sql.")";
			echo "\n7、库存处理1：".$sql."\n";
			$stmt = $pdo->prepare($sql);
			$stmt->execute();
			// 获取插入的自增ID值
			$lastInsertId_warejpise_goods_id = $pdo->lastInsertId();
			$sql = "INSERT INTO sxo_warehouse_goods_spec(warehouse_goods_id, warehouse_id,goods_id,inventory,add_time)  VALUES ";
			$sql = $sql."(";
			$sql = $sql.$lastInsertId_warejpise_goods_id.",";
			$sql = $sql."1,";
			$sql = $sql.$lastInsertId.",";
			$sql = $sql.$kuchun.",";
			$sql = $sql.time();
			$sql = $sql.")";
			echo "\n7、库存处理2：".$sql."\n";
			$stmt = $pdo->prepare($sql);
			$stmt->execute();
			// 8、更新库存
			$sql ="UPDATE sxo_goods_spec_base B
    JOIN sxo_goods A ON B.goods_id = A.id
    SET A.inventory = IF(B.inventory = 0, FLOOR(RAND() * 9501) + 500, B.inventory),
        B.inventory = IF(B.inventory = 0, FLOOR(RAND() * 9501) + 500, B.inventory)
    WHERE A.inventory = 0 OR A.inventory <> B.inventory OR B.inventory = 0";
			$stmt = $pdo->prepare($sql);
			$stmt->execute();
			echo "\n=====================\n";
			echo "<span style='color:#f00;'><h1>图书更新库存并上架成功！</h1></span>\n";
			echo "=====================\n";
		} else {
			echo "\n=====================\n";
			echo "<span style='color:#0f0;'><h1>图书已经存在，请勿重复录入！</h1></span>\n";
			echo "=====================\n";
		}
		$pdo = null;
		// 关闭数据库连接
	}
	catch (PDOException $e) {
		echo "数据库连接或SQL语句执行出错：" . $e->getMessage();
	}
}
?>
       </div>
    </div>
  </div>
</div>    
</body>
</html>
<?php
function getStringBetween($string, $start, $end) {
	$startPos = strpos($string, $start);
	if ($startPos === false) {
		return false;
	}
	$endPos = strpos($string, $end, $startPos + strlen($start));
	if ($endPos === false) {
		return false;
	}
	$length = $endPos - $startPos - strlen($start);
	return substr($string, $startPos + strlen($start), $length);
}
function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
	$method = strtoupper($method);
	$ci = curl_init();
	/* Curl settings */
	curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
	curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
	curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 0);
	/* 在发起连接前等待的时间，如果设置为0，则无限等待 */
	curl_setopt($ci, CURLOPT_TIMEOUT, 300);
	/* 设置cURL允许执行的最长秒数 */
	// 设置代理服务器
	curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
	switch ($method) {
		case "POST":
		      curl_setopt($ci, CURLOPT_POST, true);
		if (!empty($postfields)) {
			$tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
			//$tmpdatastr = is_array($postfields) ? $postfields: http_build_query($postfields);
			curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
		}
		break;
		default:
		      curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method);
		/* //设置请求方式 */
		break;
	}
	$ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
	curl_setopt($ci, CURLOPT_URL, $url);
	if($ssl) {
		curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
		// https请求 不验证证书和hosts
		curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE);
		// 不从证书中检查SSL加密算法是否存在
	}
	//curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
	curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ci, CURLOPT_MAXREDIRS, 2);
	/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
	curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ci, CURLINFO_HEADER_OUT, true);
	/*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
	$response = curl_exec($ci);
	$requestinfo = curl_getinfo($ci);
	$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
	if ($debug) {
		echo "<br>=====post data======<br>";
		var_dump($postfields);
		echo "<br>=====info=====<br>";
		print_r($requestinfo);
		echo "<br>=====response=====<br>";
		print_r($response);
	}
	return $response;
	curl_close($ci);
	//return array($http_code, $response,$requestinfo);
}
?>